package org.zanpu.timer.Utils;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.io.InputStream;
import java.util.*;

/**
 * XML服务配置解析工具
 * Created by MD on 2016/12/26.
 */
public class XmlUtils {
    private  Document doc;

    public XmlUtils(InputStream inputStream) throws DocumentException {
        Scanner scanner = new Scanner(inputStream, "UTF-8");
        String text = scanner.useDelimiter("\\A").next();
        doc = DocumentHelper.parseText(text);
    }

    /**
     * 遍历root元素下所有二级元素
     * @return 配置列表
     */
    public  List<Map<String,Object>> timerServerXML(){
        List<Map<String,Object>> mapList = new ArrayList<>();
        Element root = doc.getRootElement();
        for(Iterator iterator=root.elementIterator();iterator.hasNext();){
            mapList.add(buidMap((Element) iterator.next()));
        }
        return mapList;
    }

    /**
     * 递归xml服务配置
     * @param e 元素对象
     * @return Map
     */
    public Map buidMap(Element e){
        Map map = new HashMap();
        List list = e.elements();
        if(!list.isEmpty()) {
            list.parallelStream().forEach(aList -> {
                Element iter = (Element) aList;
                if (!iter.elements().isEmpty()) {
                    Map m = buidMap(iter);
                    map.put(iter.getName(), m);
                } else {
                    map.put(iter.getName(), iter.getText());
                }
            });
        }
        else
            map.put(e.getName(), e.getText());
        return map;
    }
}
